import {
	defineStore
} from 'pinia';
import {
	getShopList,
	updateShopItem,
	delShopItem
} from '@/api/shop.js'
import {
	error
} from '@/hooks/useToast'

// 购物车
export const useShopStore = defineStore('shop', {
	state: () => {
		return {
			shopList: [],
			total: 0,
		};
	},
	getters: {
		// 总数
		total: (state) => state.shopList.length,
		//总价
		totalPrice: (state) => {
			try {
				return state.shopList.reduce((pre, current) => {
					return Number((pre + current.amount).toFixed(2))
				}, 0)
			} catch (e) {
				return 0
			}
		},
		// 记录购物车内的商品数量和备注
		shopListData: (state) => {
			let obj = {}
			try {
				state.shopList && state.shopList.forEach(btn => {
					obj[`${btn.unitId}+${btn.productSkuId}`] = {
						qty: btn.qty,
						remark: btn.remark
					}
				})
				return obj
			} catch (e) {
				return obj
			}
		},
		// 记录商品 unitId+productSkuId : qty 用户其它地方数据回显
		shopGoodsData: (state) => {
			let obj = {}
			try {
				const item = state.shopListData
				for (let name in item) {
					obj[name] = item[name].qty
				}
				return obj
			} catch (e) {
				return obj
			}
		}
	},
	actions: {
		// 获取购物车列表数据
		async getData() {
			try {
				const res = await getShopList()
				this.shopList = res || []
			} catch (e) {
				console.log(e)
				return false
			}
		},
		// 修改购物车内商品数据
		async updateData(data) {
			try {
				await updateShopItem({
					...data
				})
				this.getData()
				return true
			} catch (e) {
				error('更新失败,请重试')
				console.log(e)
				return false
			}
		},
		//  删除购物车内商品数据
		async deleteData(data) {
			try {
				delShopItem([data.id])
				setTimeout(() => {
					this.getData()
				}, 200);
				return true
			} catch (e) {
				error('更新失败,请重试')
				console.log(e)
			}
		},
		// 购物车上的数据回显到列表上
		async dealListDataWithInShop(list) {

		}
	},
});